<link rel="stylesheet" href="nepadmin/lay/extends/dtree/dtree.css">
<link rel="stylesheet" href="nepadmin/lay/extends/dtree/font/iconfont.css">
<div class="layui-fluid" lay-title="表单组合">
    <div class="layui-card">
        <div class="layui-card-body" style="padding: 15px;">
            <form class="layui-form" action="" lay-filter="form-group">
                <div class="layui-form-item">
                    <label class="layui-form-label">部门</label>
                    <div class="layui-input-block">
                        <input type="hidden" name="deptId">
                        <input type="text" name="deptName" lay-verify="required" autocomplete="off" placeholder="请选择部门" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">用户名</label>
                    <div class="layui-input-block">
                        <input type="text" name="username" lay-verify="required" autocomplete="off" placeholder="请输入用户名称" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">登录名</label>
                    <div class="layui-input-block">
                        <input type="text" name="loginName" lay-verify="required|loginName" autocomplete="off" placeholder="请输入登录名"  class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">手机号</label>
                    <div class="layui-input-block">
                        <input type="text" name="phone" lay-verify="required|phone" autocomplete="off" placeholder="请输入手机号" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">有效</label>
                    <div class="layui-input-block">
                        <input type="radio" name="status" value="1" title="有效" checked="">
                        <input type="radio" name="status" value="0" title="无效">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">角色</label>
                    <div class="layui-input-block" id="tag_ids2">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">头像</label>
                    <div class="layui-input-inline">
                        <div class="layui-upload-list" style="margin:0">
                            <img src="/nepadmin/images/profile.jpg" style="width: 120px;height: 120px" id="srcimgurl" class="layui-upload-img">
                            <input type="hidden" id="headLogo" name="headLogo">
                        </div>
                    </div>
                    <div class="layui-input-inline layui-btn-container" style="width: auto;">
                        <button class="layui-btn layui-btn-primary" type="button" id="editimg">修改图片</button >
                    </div>
                </div>

                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button class="layui-btn" lay-submit="" lay-filter="form-group-submit">立即提交</button>
                        <button type="button" class="layui-btn layui-btn-primary" id="cancel">取消</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    layui.use(['jquery', 'api','admin', 'form','upload', 'selectM','laydate', 'layer', 'dtree'], function () {
        var $ = layui.jquery
            , layer = layui.layer
            , api = layui.api
            , laydate = layui.laydate
            , form = layui.form
            , admin = layui.admin
            , selectM = layui.selectM
            , dtree = layui.dtree
            , upload = layui.upload;
        var sysUser = {};
        var userid = POPUP_DATA.userid;
        var table = POPUP_DATA.table;
        form.render(null, 'form-group');
        laydate.render({
            elem: '#form-group-date'
        });

        if(!userid){
            userid="";
        }
        // 初始化
        admin.get({
            type: 'get',
            url: '/sysUser/userInfo?userId='+userid+'&token='+admin.loginToken,
            dataType: 'json',
            success: function(data){
                sysUser = data.sysUser;
                if(sysUser){
                    form.val("form-group", {
                        "username": sysUser.userName // "name": "value"
                        ,"phone": sysUser.phone
                        ,"headLogo": sysUser.headLogo
                        ,"loginName":sysUser.loginName
                        ,"status":sysUser.status
                        ,"deptId":sysUser.deptId
                        ,"deptName":sysUser.deptName
                    });
                    $("#srcimgurl").attr("src",sysUser.headLogo);
                }
                var selected = [];
                // 下拉权限列表
                if (data.userRoleList != null && data.userRoleList.length > 0) {
                    $.each(data.userRoleList,function (i,v) {
                        selected.push(v.roleId);
                    });
                }
                //多选标签-所有配置
                var tagIns2 = selectM({
                    //元素容器【必填】
                    elem: '#tag_ids2'
                    //候选数据【必填】
                    ,data: data.sysRoleList
                    //默认值
                    ,selected: selected
                    //最多选中个数，默认5
                    ,max : 6
                    //input的name 不设置与选择器相同(去#.)
                    ,name: 'tag2'
                    //值的分隔符
                    ,delimiter: ','
                    ,tips:'请选择角色'
                    //候选项数据的键名
                    ,field: {idName:'id',titleName:'roleName'}
                });
            }
        });

        // 上传图片处理
        var uploadInst = upload.render({
            elem: '#editimg'
            ,url: '/fileUpload'
            ,field: 'myfiles'
            ,before: function(obj){
                //预读本地文件示例，不支持ie8
                /*obj.preview(function(index, file, result){
                    $('#srcimgurl').attr('src', result); //图片链接（base64）
                });*/
            }
            ,done: function(res){
                //如果上传失败
                if(res.code != '0'){
                    return layer.msg('上传失败');
                }
                //上传成功,作为上传参数
                console.log(res.data);
                $('#srcimgurl').attr('src', res.data[0]); //图片链接（base64）
                $("#headLogo").val(res.data[0]);
            }
        });

        // 弹窗
        $("input[name='deptName']").on("click",function(){
            layer.open({
                type: 1,
                title: "选择树",
                area: ["400px", "80%"],
                content: '<ul id="openTree1" class="dtree" data-id="0"></ul>',
                btn: ['确认'],
                success: function(layero, index){
                    var treeUrl = '/sysDept/queryDeptListR?token=' + admin.loginToken;
                    var tree = dtree.render({
                        //  obj: $(layero).find("#openTree1"),    如果直接用elem加载不出来，则可以使用这个方式加载jquery的DOM
                        elem: "#openTree1",
                        method: "get",
                        dataStyle: "layuiStyle",
                        response: {statusCode: 0, rootName: "sysDeptList",title:"name"},
                        initLevel: 1,
                        dot: false,
                        skin: "zdy",  // 自定义风格
                        url: treeUrl,
                        done:function (data, obj) {
                            if (sysUser && sysUser.deptId) {
                                dtree.dataInit("openTree1", sysUser.deptId);
                            }
                        }
                    });
                    // 绑定节点的双击
                    /*dtree.on("nodedblclick('openTree1')", function(param){
                     });*/
                },
                yes: function(index, layero) {
                    var param = dtree.getNowParam("openTree1"); // 获取当前选中节点
                    if (!param.isLeaf) {
                        layer.msg("请选择末级节点");
                        return false;
                    }
                    $("input[name='deptId']").val(param.nodeId);
                    $("input[name='deptName']").val(param.context);
                    layer.close(index);
                }
            });
        });

        /* 自定义验证规则 */
        form.verify({
            loginName: function (value) {
                if (!verifyLoginName(value)) {
                    return "您输入的登录名已被注册,请重新输入";
                }
            }
        });

        /* 监听提交 */
        form.on('submit(form-group-submit)', function (data) {
            var field = data.field;
            var userDate={};
            userDate.userName = field.username;
            userDate.headLogo = field.headLogo;
            userDate.loginName = field.loginName;
            userDate.deptId = field.deptId;
            userDate.status = field.status;
            userDate.phone = field.phone;
            userDate.roleIds = field.tag2;
            var url = "/sysUser/save";
            if(userid){
                url = "/sysUser/update?_method=PUT";
                userDate.id=userid;
            }
            admin.post({
                url:url,
                contentType: "application/json",
                data:JSON.stringify(userDate),
                headers: {
                    "token": admin.loginToken
                },
                success:function(res){
                    if (res.code == 0){
                        // 提醒保存成功，关闭当前弹窗
                        layer.msg(res.msg);
                        layer.closeAll();
                        //刷新
                        table.reload('list-table-user',{
                            url:'/sysUser/page?token='+admin.loginToken,
                            page:{
                                curr:1
                             }
                        })

                    } else {
                        layer.msg(res.msg);
                    }
                }
            });
            return false;
        });

        $("#cancel").on("click",function () {
            // 关闭弹窗
            //layer.close(layer.index);
            layer.closeAll('page');
        });

        function verifyLoginName(loginName) {
            var resCode=true;
            admin.get({
                type: 'get',
                async:false,
                url: '/sysUser/checkUnique?userId='+userid+'&loginName='+loginName,
                dataType: 'json',
                success: function(data){
                    if (data.code == 500){
                        resCode=false;
                    }
                },
                error:function(){
                    return false;
                }
            });
            if(!resCode){
                return false;
                //return "您输入的登录名已被注册,请重新输入";
            }
            return true;
        }
    });
</script>